<template>
	<view class="upload-list-box">
		<view class="top-pane" @click="back">
			<uni-icons type="left" size="12" color="#0055ff"></uni-icons>上一步
		</view>
		<view class="upload-list">
			<uni-file-picker :value="fileLists" file-mediatype="pdf" mode="grid" @select="select" @progress="progress"
				@success="success" @fail="fail" />
		</view>
		<view class="btn">
			<button style="margin: 20rpx" type="primary" @click="closeAdd">
				提交
			</button>
		</view>
	</view>
</template>

<script>
	import {
		api,
		ConstUtil
	} from '@/util/api.js'
	import BASEURL from '@/util/request.js'
	export default {
		props: {
			relationId: '',
			type: 0, // 1销售合同，1采购合同，2 报销
		},
		data() {
			return {
				fileLists: [],
				uploadUrl: 'http://manager.qy-zb.com', // 上传文件基URL
			}
		},
		methods: {
			// 获取上传状态
			select(e) {
				let suffix = e.tempFiles[0].extname
				if (suffix != 'jpg' && suffix != 'png' && suffix != 'jpeg' && suffix != 'pdf' && suffix != 'doc' &&
					suffix != 'docx') {
					return uni.showToast({
						icon: "none",
						title: '文件类型不正确'
					})
				}
				let formData = {
					'business': ConstUtil.BUSINESS_PROCURE_CONTRACT_INFO,
					'relationId': this.relationId,
					'type': ConstUtil.FILE_TYPE_CONTRACT
				}
				// 报销
				if (this.type == 2) {
					formData = {
						'business': ConstUtil.BUSINESS_EXPENSE_INFO,
						'relationId': this.relationId,
						'type': ConstUtil.FILE_TYPE_INVOICE
					}
				}
				const tempFilePaths = e.tempFilePaths;
				uni.uploadFile({
					url: this.uploadUrl + api.SaveFile,
					filePath: tempFilePaths[0],
					name: 'multipartFile',
					formData: formData,
					// 成功函数
					success: (res) => {
						// uni.uploadFile默认在外面包了一层data
						console.log('上传成功', res.data);
						// uni.uploadFile返回来的结果默认是JSON格式字符串，需要用JSON.parse转换成js对象
						console.log('上传数据转换', JSON.parse(res.data));
					},
					// 失败提示用户重新上传
					fail: error => {
						console.log('失败', error);
					}
				})
			},
			closeAdd() {
				// 关闭当前添加界面，调用父组件AddContract里方法，返回到具体列表界面
				uni.$emit('saveBack', this.type)
			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},
			// 上传成功
			success(e) {
				console.log('上传成功')
			},
			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			back() {
				// 根据自己所在第几个tab
				let tab = 1
				if (this.type == 1) {
					tab = 0 // 销售合同
				}
				if (this.type == 2) {
					tab = 1 // 报销
				}
				uni.$emit('changeTab', tab)
			}
		},
	}
</script>

<style>
	@import '@/static/css/UploadAnnex.css';
</style>